package com.conero.yangsu.lib;

import com.conero.yangsu.entity.AdminEntity;
import com.conero.yangsu.mapper.AdminMapper;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

public class AdminSecurity {
    public static final String AdminSessionKey = "admin";

    // 生成admin session数据
    public static Object makeAdminSessionData(AdminEntity adminEntity) {
        if (adminEntity == null) {
            return null;
        }
        return adminEntity.sessionData();
    }

    // 获取用户信息
    public static Object getAdminInfo(HttpSession session) {
        return session.getAttribute(AdminSessionKey);
    }

    // 密码验证
    public static boolean verifyPassword(String rawPassword, AdminEntity admin) {
        MessageDigest md;
        try {
            rawPassword = rawPassword.trim();
            md = MessageDigest.getInstance("SHA-256");
            md.update(admin.getSaltHash().getBytes(StandardCharsets.UTF_8));    // 先加盐值
            md.update(rawPassword.getBytes(StandardCharsets.UTF_8));
            return byte2Hex(md.digest()).equals(admin.getCypher());
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("256-加密错误");
        }
        return false;
    }

    // 用户密码生成
    public static boolean createPassword(String rawPassword, AdminEntity admin) {
        MessageDigest md;
        try {
            String salt = RandomStringUtils.randomAlphanumeric(15);
            admin.setSaltHash(salt);
            rawPassword = rawPassword.trim();
            md = MessageDigest.getInstance("SHA-256");
            md.update(salt.getBytes(StandardCharsets.UTF_8));    // 先加盐值
            md.update(rawPassword.getBytes(StandardCharsets.UTF_8));
            // 密码保存
            admin.setCypher(byte2Hex(md.digest()));
            return true;
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("256-加密错误");
        }
        return false;
    }

    // 将byte转为16进制
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuffer = new StringBuilder();
        String temp = null;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    // 用于测试的自动用户登录
    public static void autoLoginByUid(Long id, AdminMapper adminMapper, HttpSession session) {
        Optional<AdminEntity> admin = adminMapper.findById(id);
        if (!admin.isPresent()) {
            return;
        }
        session.setAttribute(AdminSecurity.AdminSessionKey,
                AdminSecurity.makeAdminSessionData(admin.get()));
    }
}
